package com.leador.map.location.log;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Binder;
import android.os.IBinder;

import com.leador.map.location.Const;
import com.leador.map.location.util.NetUtil;
import com.leador.map.location.util.Utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 *
 */
public class UploadService extends Service {
    private List<File> lstFile = new ArrayList<File>();
    private UploadBinder upBinder = new UploadBinder();

    @Override
    public IBinder onBind(Intent intent) {
        Utils.writeCat("up|on bind");
        return upBinder;
    }

    @Override
    public void onCreate() {
        Utils.writeCat("up|on create");
    }

    @Override
    public void onStart(Intent intent, int iStart) {
        Utils.writeCat("up|on start");
        if (lstFile.size() > 0) {
            return;
        }
        File fileDir = new File(Storage.getLogDir(UploadService.this));
        if (!fileDir.isDirectory()) {
            return;
        }
        File[] fa = fileDir.listFiles();
        if (fa.length == 0) {
            Utils.writeCat("up|no zip existed");
            return;
        }
        lstFile.clear();
        for (File file : fa) {
            if (file.getName().indexOf(Const.strZipLog) != -1 && file.exists()) {
                Utils.writeCat("up|add \"", file.getName(), "\"");
                lstFile.add(file);
            }
        }
        upZip();
    }

    @Override
    public void onDestroy() {
        Utils.writeCat("up|on destroy");
        lstFile.clear();
        upBinder = null;
        super.onDestroy();
    }

    /**
     * 上传ZIP压缩日志
     *
     */
    private void upZip() {
        if (lstFile.size() == 0) {
            Utils.writeCat("up|no zip existed");
            return;
        }
        String strCs = Context.CONNECTIVITY_SERVICE;
        ConnectivityManager cm = null;
        cm = (ConnectivityManager) Utils.getService(this, strCs);
        int iNetworkType = NetUtil.getNetworkType(cm.getActiveNetworkInfo());
        cm = null;
        if (iNetworkType == -1) {
            Utils.writeCat("up|no net available");
            return;
        }
        Thread thread = new Thread() {
            public void run() {
                StringBuffer sbUrl = new StringBuffer();
                sbUrl.append(Const.strUp);
                sbUrl.append("&zei=").append(Const.strImei);
                sbUrl.append("&zsi=").append(Const.strImsi);
                while (lstFile.size() > 0) {
                    final File file = lstFile.get(0);
                    Utils.writeCat("up|pre \"", file.getName(), "\"");
                    if (!file.exists()) {
                        Utils.writeCat("up|\"", file.getName(), "\"not existed");
                        lstFile.remove(file);
                        continue;
                    }
                    if (doUp(sbUrl.toString(), file)) {
                        file.delete();
                        lstFile.remove(0);
                    }
                    try {
                        Thread.sleep(Const.lMinUp);
                    } catch (Exception e) {
                        Utils.printE(e);
                    }
                }
                sbUrl.delete(0, sbUrl.length());
                sbUrl = null;
            }
        };
        thread.start();
    }

    /**
     * 执行上传ZIP压缩日志
     *
     * @param strUrl
     * @param file
     * @return boolean
     */
    private boolean doUp(String strUrl, File file) {
        boolean bSuccess = false;
        HttpClient hc = new DefaultHttpClient();
        Utils.setTimeOut(hc.getParams(), Const.iUpTimeout);
        HttpPost hp = new HttpPost(strUrl);
        FileEntity fe = new FileEntity(file, "binary/octet-stream");
        fe.setContentEncoding(HTTP.UTF_8);
        hp.setEntity(fe);
        HttpResponse hr = null;
        try {
            hr = hc.execute(hp);
            int iStatusCode = hr.getStatusLine().getStatusCode();
            HttpEntity he = hr.getEntity();
            String strRespContent = Utils.isToStr(he.getContent());
            if (iStatusCode != HttpStatus.SC_OK) {
                Utils.writeCat("up|err:status code ", iStatusCode);
            } else if (!strRespContent.equals("true")) {
                Utils.writeCat("up|err:resp content ", strRespContent);
            } else {
                Utils.writeCat(hr.getStatusLine(), "#", strRespContent);
                bSuccess = true;
            }
        } catch (java.net.UnknownHostException e) {
            Utils.writeCat("unknown host e");
        } catch (Exception e) {
            Utils.printE(e);
        } finally {
            if (hp != null) {
                hp.abort();
                hp = null;
            }
            if (hc != null) {
                hc.getConnectionManager().shutdown();
                hc = null;
            }
            fe = null;
            hr = null;
        }
        return bSuccess;
    }

    /**
     * UPLOAD的Binder类
     *
     */
    public class UploadBinder extends Binder {
        public UploadService getServ() {
            return UploadService.this;
        }
    }
}